Home |
| Latest | About | Random
# Practice Problems Set 1. Some basic practice to check for your understanding so far. This is by no means sufficient for exam preparation, you will still need to practice read and write a lot of code! Write each space character as ␣ when it matters. Unless a full program is shown, assume each snippet is inside `main()` of a program that starts with ```cpp #include #include #include using namespace std; ``` ## Part 1. Errors and Variables Practice 1. Is each one a build error, runtime error, undefined behavior, or logic error? Explain briefly. (a) ```cpp #include int main() { cout << "Hi"; return 0; } ``` (b) ```cpp #include using namespace std int main() { cout << "Hi"; return 0; } ``` (c) ```cpp cout >> "Hi"; ``` (d) ```cpp int n; cout << n; ``` (e) ```cpp string s = "cat"; cout << s.at(3); ``` (f) ```cpp string s = "cat"; cout << s[10]; ``` (g) ```cpp int n = 5; int n = 6; ``` (h) ```cpp n = 5; int n; ``` (i) ```cpp // The goal is to print the total cost of 4 items that cost 3 dollars each. int price = 3, qty = 4; cout << "Total: " << price + qty; ``` Practice 2. Which of these are allowed as variable names? For each one that isn't, say why. ``` my_int 2fast _x int total-sum Total numberOfCats x2 my score return ``` Practice 3. Write down the values of `i`, `j`, and `k` after each line. ```cpp int i = 1, j = 2, k = 3; i = j; j = i + k; k = j + k; i = k - j; ``` Practice 4. ```cpp int a = 3, b = 8; a = b; b = a; ``` (a) What are `a` and `b` now? (b) Fix the code so it swaps `a` and `b`, by using a third variable `x`. ## Part 2. Arithmetic and Types Practice 5. What value does each expression produce? (a) `17 / 5` (b) `17 % 5` (c) `17.0 / 5` (d) `1 / 2 * 4.0` (e) `4.0 * 1 / 2` (f) `2 + 3 * 4` (g) `(2 + 3) * 4` (h) `10 - 4 - 3` (i) `static_cast(3.99)` Practice 6. What value does each expression produce? (a) `-7 / 2` (b) `-7 % 2` (c) `7 % -2` (d) `-8 % 3` (e) `(-8 / 3) * 3 + (-8 % 3)` Practice 7. (a) What is the value of `k` after each line runs? Each line uses the result of the line before it. ```cpp int k = 10; k += 5; k *= 2; k -= 4; k /= 3; k %= 4; ``` (b) What does this print? Each line uses the value of `x` left by the line before it. Then explain the difference between `x++` and `++x`. ```cpp int x = 5; cout << x++ << endl; cout << x << endl; cout << ++x << endl; cout << x-- << endl; cout << x << endl; ``` Practice 8. (a) `int n = 137;` Using `/` or `%`, write expressions that give `13`, `7`, and `1`. (b) You owe someone 87 cents. Using `/` and `%`, find - how many quarters (25 cents) you can give, - how many cents are left after that, - how many dimes (10 cents) fit in what is left, - and how many pennies are left at the end. Practice 9. Number the days `0` = Sunday, `1` = Monday, ..., `6` = Saturday. Today is Friday, so `int day = 5;` Use `%` to work out which day it will be (a) 3 days from now (b) 10 days from now (c) 3000 days from now (d) 10 days ago (Careful: `%` can give a negative number.) (e) How many full weeks are in 3000 days, and how many days are left over? Practice 10. Each line has a bug. What does it produce, and how would you fix it? (a) ```cpp // the volume of a sphere: (4/3) * pi * r^3 const double PI = 3.14159; double r = 2.0; double volume = 4 / 3 * PI * pow(r, 3); ``` (b) ```cpp // the percent score for 17 correct out of 20 int correct = 17, total = 20; cout << correct / total * 100; ``` Practice 11. ```cpp double a = 0.1; cout << (a + a + a == 0.3); ``` What do you think this prints? Why? Practice 12. What does each statement print? Note: You don't need to memorize any ASCII codes. All you need to know is that `'a'` to `'z'`, `'A'` to `'Z'`, and `'0'` to `'9'` each have codes that are in order. (a) `cout << static_cast('A' + 2);` (b) `cout << static_cast('a' + 20);` (c) `cout << '7' - '0';` (d) `cout << static_cast('m' - 'a' + 'A');` (e) `cout << ('b' < 'd');` Then write an expression for each: (f) Given `char d = '6';` produce the `int` `6`. (g) Given `char c = 'r';` produce the `char` `'R'`. Your expression should work for any lowercase letter. Practice 13. What does this program print? ```cpp #include using namespace std; int main() { int x = 5; cout << (x == 10) << endl; cout << (x = 10) << endl; cout << (x == 10) << endl; bool b = 0.5; bool z = 0; cout << b << " " << z << endl; double a = 1.9; int n = a; cout << n << endl; cout << boolalpha << (3 + 2 == 5) << endl; return 0; } ``` Practice 14. What does each one print? You don't need the exact digits. Saying "a huge positive number" is enough, as long as you can explain why. (a) ```cpp string s = "Hello"; cout << s.length() - 10; ``` (b) ```cpp unsigned int x = 0; x--; cout << x; ``` (c) ```cpp int i = -1; unsigned int u = 0; cout << i + u; ``` ## Part 3. Strings Practice 15. `string word = "banana";` What does each statement print? (a) `cout << word.length();` (b) `cout << word.at(2);` (c) `cout << word.find("an");` (d) `cout << word.rfind("an");` (e) `cout << (word.find("x") == string::npos);` (f) `cout << word.substr(2);` (g) `cout << word.substr(0, 3);` Practice 16. Suppose `string name` holds some word with at least 3 characters. Its value is unknown. Write an expression for each of the following: (a) the first character of `name` (b) the last character of `name` (c) `name` with `'!'` added to the end (d) the first three characters of `name` Practice 17. What does this program print? ```cpp #include #include using namespace std; int main() { string a = "sun", b = "flower"; string c = a + b; cout << c << " " << c.length() << endl; c += "s"; cout << c << endl; cout << b + a << endl; return 0; } ``` Practice 18. (a) What does this print? ```cpp string s1(5, '*'); string s2; cout << s1 << "|" << s2 << "|" << s2.length(); ``` (b) Which of these lines are build errors? Treat each one as its own separate program. ```cpp string a = "Hi"; string b = a + " there"; string c = "Hi" + " there"; string d = "Hi"; d += " there"; string e = "Hi" + a; ``` Practice 19. ```cpp string s = "apple"; ``` What does each one give? (a) `s.substr(1, 100)` (b) `s.substr(5)` (c) `s.substr(2, 0)` (d) `s.substr(6)` Practice 20. What does each one give? (a) `stod("2.5") * 2` (b) `stod("-3.5abc")` (c) `stod("12 apples")` (d) `stod("abc")` Practice 21. What does this print? You can use `+` and `+=` to join a string with another string or with a single char. ```cpp string word = "art"; string a = word + 's'; string b = 'p' + word; string c = 'c' + word + 's'; cout << a << endl; cout << b << endl; cout << c << endl; word += "ist"; cout << word << endl; word += 's'; cout << word << endl; ``` Practice 22. ```cpp const string animal = "tiger"; ``` Which lines are build errors? Treat each one as its own separate line. (a) `cout << animal.length();` (b) `animal = "lion";` (c) `animal.at(0) = 'T';` (d) `string big = animal; big.at(0) = 'T';` (e) `cout << animal.substr(1);` (f) `animal += "s";` Practice 23. The goal of this code is to check whether `'x'` appears in `str`. ```cpp string str = "abc"; if (str.find('x')) { cout << "found x"; } else { cout << "no x"; } ``` (a) What does it print? (b) What would it print if we searched for `'a'` instead of `'x'`? (c) Fix the condition. ## Part 4. Input Practice 24. The user types `New York` followed by `ENTER` key. What does the variable hold in each case? (a) `string city; cin >> city;` (b) `string city; getline(cin, city);` (c) `char c; cin >> c;` Now the user types `New York` `ENTER` key, then `Los Angeles` `ENTER` key. What do `a` and `b` hold in each case? (d) `string a, b; cin >> a; getline(cin, b);` (e) `string a, b; getline(cin, a); getline(cin, b);` (f) `string a, b; cin >> a >> b;` (g) `string a, b; getline(cin, a); cin >> b;` Now the user types `19` `ENTER` key, then `New York` `ENTER` key, then `Los Angeles` `ENTER` key. ```cpp int age; string a, b; cin >> age; getline(cin, a); getline(cin, b); ``` (h) What do `age`, `a`, and `b` hold? (i) Where could you add the line `cin.ignore();` so that `a` holds `New York` and `b` holds `Los Angeles`? Practice 25. Write a complete program that asks for the user's first name and age, then prints `Hi Alex, next year you will be 20.` In this example, the user entered `Alex` and `19`. Practice 26. The user types `cat` followed by `ENTER` key. What does this print? ```cpp char a = cin.get(); char b = cin.get(); cout << b << a; ``` Practice 27. The user types `xyz` followed by `ENTER` key. What does this print? ```cpp char p = cin.peek(); char g = cin.get(); cout << p << g; ``` How is `peek` different from `get`? Practice 28. The user types `hello` followed by `ENTER` key. What does this print? ```cpp cin.ignore(3); char c = cin.get(); cout << c; ``` Practice 29. The user types `7 dogs` followed by `ENTER` key. ```cpp int n; char c; cin >> n; c = cin.get(); cout << n << "[" << c << "]"; ``` (a) What does it print? (b) What does it print if `c = cin.get();` is replaced by `cin >> c;` ? Practice 30. Write code that uses `cin.peek()` to check whether the next character typed is a digit. - If it is a digit, read an `int` and print `number` followed by the `int`. - Otherwise, read a `string` and print `word` followed by the `string`. Example: the input `42` prints `number 42`, and the input `pizza` prints `word pizza`. ## Part 5. Scope and Loops Practice 31. Each program has a build error. Find it and explain. (a) ```cpp int a = 1; if (a > 0) { int b = 2; cout << a + b << endl; } cout << b << endl; ``` (b) ```cpp for (int i = 0; i < 3; i++) { cout << "hi"; } cout << i; ``` Practice 32. Write a for loop that prints `10 9 8 7 6 5 4 3 2 1 ` (with a space after each number). Practice 33. What does this print? ```cpp int total = 0; for (int i = 1; i <= 5; i++) { total += i; } cout << total; ``` Practice 34. What does this print? ```cpp int n = 1; while (n < 50) { cout << n << " "; n *= 3; } ``` Practice 35. (a) What does this print? ```cpp for (int i = 1; i < 100; i *= 2) { cout << i << " "; } ``` (b) What happens if `int i = 1` is changed to `int i = 0` ? Practice 36. Write a loop that adds up all the even numbers from 2 to 100, then prints the sum. Practice 37. Write a loop that computes `6! = 6 * 5 * 4 * 3 * 2 * 1` and prints it. Practice 38. How many times does each loop print "hi"? (a) ```cpp for (int i = 0; i < 10; i += 2) { cout << "hi"; } ``` (b) ```cpp for (int i = 10; i > 0; i--) { cout << "hi"; } ``` (c) ```cpp for (int i = 0; i < 3; i++) { for (int j = 0; j < 4; j++) { cout << "hi"; } } ``` Practice 39. What does each one print? (a) ```cpp for (int i = 1; i <= 10; i++) { if (i == 5) { break; } cout << i; } ``` (b) ```cpp for (int i = 1; i <= 6; i++) { if (i % 3 == 0) { continue; } cout << i; } ``` (c) ```cpp int n = 0; while (true) { n += 4; if (n > 10) { break; } } cout << n; ``` Practice 40. What does this print? ```cpp for (int i = 1; i <= 4; i++) { for (int j = 1; j <= i; j++) { cout << j; } cout << endl; } ``` Practice 41. What does this print? ```cpp for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 3; j++) { if (i == j) { cout << "*"; } else { cout << "."; } } cout << endl; } ``` Then change one thing in the if condition so that it prints the `*` on the other diagonal instead: ``` ..* .*. *.. ``` Practice 42. `string word` holds a word that is all lowercase. Write a loop that changes every letter to uppercase, so `hello` becomes `HELLO`. What type should the loop index be, and why? ## Part 6. Conditions Practice 43. Write a C++ condition for each sentence. Use only comparison operators (`==, !=, <, <=, >, >=`), logical operators (`&&, ||, !`), and arithmetic operators such as `%`. Each condition should evaluate to true exactly when the sentence is true. (a) `int x` is between `1` and `10` (including `1` and `10`). (b) `int x` is even. (c) `int age` is under `13` or over `65`. (d) `char c` is an uppercase letter. Practice 44. ```cpp bool t = true, f = false; ``` Does each expression evaluate to `1` or `0`? (a) `t && f` (b) `t || f` (c) `!t || f` (d) `!(t && f)` (e) `(t || f) && !f` Practice 45. ```cpp if (score >= 90) { cout << "A"; } else if (score >= 80) { cout << "B"; } else if (score >= 70) { cout << "C"; } else { cout << "F"; } ``` What does this print if score is (a) `85` (b) `90` (c) `69` (d) `70` Practice 46. A year is a leap year if it is divisible by 4, except that a year divisible by 100 is a leap year only if it is also divisible by 400. ```cpp int year; cin >> year; bool div_by_4 = (year % 4 == 0); bool div_by_100 = (year % 100 == 0); bool div_by_400 = (year % 400 == 0); bool leap; if (div_by_4) { if (div_by_100) { if (div_by_400) { leap = true; } else { leap = false; } } else { leap = true; } } else { leap = false; } cout << leap; ``` (a) What does it print for the years `2024`, `2023`, `1900`, and `2000`? (b) Replace the whole if-else block with a single line ```cpp bool leap = ... ; ``` using only `div_by_4`, `div_by_100`, `div_by_400`, and `&&`, `||`, `!`. (c) Is there a second, different-looking answer to (b) that also works? Try to find one. ## Part 7. Scope and Shadowing Practice 47. (a) What does this print? ```cpp int x = 1; if (x > 0) { int x = 5; cout << x << endl; } cout << x << endl; ``` (b) What does it print if `int x = 5;` is changed to `x = 5;` ? Practice 48. (a) What does this print? ```cpp int total = 100; for (int i = 0; i < 3; i++) { int total = i * 10; cout << total << " "; } cout << total; ``` (b) What does it print if `int total = i * 10;` is changed to `total = i * 10;` ? Practice 49. (a) What does this print? ```cpp int i = 7; for (int i = 0; i < 3; i++) { cout << i; } cout << " " << i; ``` (b) What does it print if `for (int i = 0; ...` is changed to `for (i = 0; ...` ? Practice 50. The goal of this code is to print `123`. ```cpp int n = 0; while (n < 3) { int count = 0; count++; n++; cout << count; } ``` (a) What does it actually print? Why? (b) Move one line to fix it. Practice 51. What happens when this runs? Explain. ```cpp int k = 0; while (k < 3) { int k = 10; cout << k << " "; k++; } ``` ## Part 8. Input Loops and Binary Practice 52. ```cpp char response; int rounds = 0; while (true) { rounds++; cout << "Again? "; cin >> response; if (response == 'n') { break; } } cout << rounds; ``` The user types `y` `ENTER` key, then `y` `ENTER` key, then `n` `ENTER` key. (a) How many times is `Again? ` printed, and what is the final value of `rounds`? (b) Now replace `cin >> response;` with `response = cin.get();` and type the same input. How many times is `Again? ` printed now? Why is it different? Practice 53. This program counts how many numbers the user types on one line. ```cpp int number; int count = 0; while (true) { cin >> number; count++; if (cin.peek() == '\n') { break; } } cout << count; ``` What happens for each input (each one followed by `ENTER` key)? (a) `5 1 2 5 6 9` (b) `␣␣␣1␣␣␣2␣3` (c) `1␣2␣3␣` (Note the space at the end.) (d) Where could you add the line `while (cin.peek() == ' ') { cin.ignore(); }` to fix (c)? Practice 54. (a) Write 50 in binary. (b) Write 13 in binary. (c) What number is binary 1011? (d) What number is binary 100000? ## More. Practice 55. FizzBuzz is a classic programming warm-up. For each number from 1 to 15, print - `Fizz` if the number is divisible by 3, - `Buzz` if it is divisible by 5, - `FizzBuzz` if it is divisible by both 3 and 5, - and otherwise the number itself, with a space after each one. (a) Write the loop. (b) A student wrote the checks in a different order as follows. What does this loop print? Write out its output. Does it do what FizzBuzz is supposed to do? Why or why not? ```cpp for (int i = 1; i <= 15; i++) { if (i % 3 == 0) { cout << "Fizz"; } else if (i % 5 == 0) { cout << "Buzz"; } else if (i % 15 == 0) { cout << "FizzBuzz"; } else { cout << i; } cout << " "; } ```